package io.hellsinger.vortex.component.layout

import io.hellsinger.vortex.data.Line
import io.hellsinger.vortex.ui.component.StorageTextEditorView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.withContext

class DefaultTextLayout {
    @OptIn(DelicateCoroutinesApi::class)
    private val context = newFixedThreadPoolContext(nThreads = 2, name = "TextLayout")
    private val scope: CoroutineScope = CoroutineScope(context + SupervisorJob())

    private val lines = mutableListOf<Line>()

    private var view: StorageTextEditorView? = null

    private var currentMaxLength = 0

    val lineCount: Int
        get() = lines.size

    fun lines(): List<Line> = lines

    val height: Int
        get() = lineCount

    val width: Int
        get() = currentMaxLength

    var maxTextIndex: Int = -1
        private set

    val maxTextLength: Int
        get() = currentMaxLength

    fun getLineAt(index: Int) = lines[index]

    fun close() {
        view = null
        context.cancel()
        context.close()
    }

    suspend fun setLines(lines: List<Line>) =
        withContext(context) {
            this@DefaultTextLayout.lines.clear()
            this@DefaultTextLayout.lines.addAll(lines)

            currentMaxLength = 0
            maxTextIndex = -1
            lines.forEachIndexed { index, line ->
                if (line.length > currentMaxLength) {
                    currentMaxLength = line.length
                    maxTextIndex = index
                }
            }
        }

    fun appendLine(line: Line) {
        lines.add(line)
        if (line.length > currentMaxLength) {
            currentMaxLength = line.length
            maxTextIndex = lines.lastIndex
        }
    }
}
